package com.company.zhishidian.socket;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.*;

public class Server {
    public static void main(String[] args) {
        try {
            ServerSocket server = new ServerSocket(8888);
            System.out.println("服务器已经启动");
            //服务端唯一的一个输入界面
            Scanner input = new Scanner(System.in);

            ArrayBlockingQueue<PrintWriter> clientQueue = new ArrayBlockingQueue<>(10);

            ExecutorService pool = new ThreadPoolExecutor(
                    10,
                    10,
                    10,
                    TimeUnit.SECONDS,
                    new SynchronousQueue<>(),
                    new ThreadFactory() {
                        @Override
                        public Thread newThread(Runnable r) {
                            Thread th = new Thread(r);
                            th.setName("客户端线程");
                            return th;
                        }
                    }
            );
            ExecutorService singlePool = Executors.newSingleThreadExecutor();

            //写线程 嘴巴
            singlePool.execute(()->{

                while (true) {
                    String msg = input.nextLine();
                    for(PrintWriter out:
                            clientQueue) {
                        out.println(msg);
                    }
                }
            });

            while (true) {
                Socket socket = server.accept();//等待状态
                //对应的每个客户端
                pool.execute(()->{
                    System.out.println("某一个客户端已经连接上");
                    try {
                        Scanner in = new Scanner(socket.getInputStream());//向自己输入
                        PrintWriter out = new PrintWriter(
                                socket.getOutputStream(), true);
                        clientQueue.put(out);
                        while (true) {
                            String msg = in.nextLine();//IO阻塞
                            System.out.println(msg);
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                });
            }

            } catch(IOException e){
                e.printStackTrace();
            }

    }
}
